#!/usr/bin/env python

import model
import progressbar
import resource.string.app

from .._console import Console

class Saver(Console):

    def run(self):
        self.greeting(resource.string.app)
        
        self.progress('Opening database... ')
        db = self.openDb()
        if not db:
            self.fail('Error >_<\n')
        else:
            self.success('OK ^_^v\n')
            modem = self.loadModem()
            if modem:
                # Set modem to PDU mode
                modem.cmgf(0)
                
                # Set modem prefered storage here
                cpmses = {'SIM Memory': '"SM","SM","SM"',
                          'Mobile Equipment': '"ME","ME","ME"'}
                for key in cpmses:
                    modem.cpms(cpmses[key])
                    
                    self.progress('Reading message from %s... ' % key)
                    pdus = modem.cmgl(4)
                    self.success('OK ^_^v\n')
                    
                    self.info('Found %s PDUs.\n' % len(pdus))
                    if pdus:
                        if self.save(pdus, db):
                            self.delete(modem, pdus)
            
        self.farewell()
        
    def loadModem(self):
        self.progress('Opening modem... ')
        modem = super(Saver, self).loadModem()
        if modem: self.success('OK ^_^v\n')
        else: self.fail('Error >_<\n')
        return modem
    
    def save(self, pdus, db):
        '''Read PDU from modem and save to database'''
        
        if not self._silent:
            total = len(pdus)
            simple = progressbar.SimpleProgress()
            percentage = progressbar.Percentage()
            bar = progressbar.Bar(marker='#', left='[', right=']')
            eta = progressbar.ETA()
            widgets = ['Saving ', simple, ' ', bar, ' ', percentage, ' ', eta]
            progress = progressbar.ProgressBar(widgets=widgets, maxval=total)
            progress.start()
        
        messages = []
        for index, key in enumerate(pdus):
            message = model.Message()
            message.pdu = pdus[key]
            messages.append(message)
            if not self._silent: progress.update(index + 1)
            
        if not self._silent: progress.finish()
        
        self.progress('Committing changes to database... ')
        db.add_all(messages)
        try: db.commit()
        except:
            self.fail('Error >_<\n')
            return False
        else:
            self.success('OK ^_^v\n')
            return True
    
    def delete(self, modem, pdus):
        '''Delete PDUs from modem'''
        
        if not self._silent:
            total = len(pdus)
            simple = progressbar.SimpleProgress()
            percentage = progressbar.Percentage()
            bar = progressbar.Bar(marker='#', left='[', right=']')
            eta = progressbar.ETA()
            widgets = ['Deleting ', simple, ' ', bar, ' ', percentage, ' ', eta]
            progress = progressbar.ProgressBar(widgets=widgets, maxval=total)
            progress.start()
            
        for index, key in enumerate(pdus):
            modem.cmgd(key)
            if not self._silent: progress.update(index + 1)
        
        if not self._silent: progress.finish()
        